writing in a file's particular column number of every line during runtime

Given a particular line number and a corresponding column number, can i write something in the file during run time?

For example x=1 and during runtime i want to write the value of x in column 100 of every line of a given file, then how shud that be done?

Thanks

assuming the file is delimited with spaces:

# Process 'file' and save to temp file /tmp/$$
# This example replaces column 100, line 32, with the string "x".
awk -v L=32 -v C=100 -v V="x" '{ if(NR == LINE) $COL=VAL } 1 < file > /tmp/$$
# Overwrite 'file' with contents of /tmp/$$
cat /tmp/$$ > file
# delete temp file
rm /tmp/$$

@Corona688, shouldn't it be

awk -v LINE=32 -v COL=100 -v VAL="x" '{ if(NR == LINE) $COL=VAL } 1' < file > /tmp/$$

:wink:

1 Like

i dont find any change in the file after i execute this command

Give examples of lines in your file.

i have this following file named test.txt whose content is

Hello
World

Whats Up?

and i execute the following command
x="Hey"
awk -v LINE=3 -v COL=1 -v VAL="x" '{ if(NR == LINE) $COL=VAL } 1' test.txt /tmp/$$

Now the output should be
Hello
World
Hey
Whats Up?

BUT thats not happening

cat INPUTFILE
Hello 
World

Whats Up?
 
x=Hey; awk -v LINE=3 -v COL=1 -v VAL="$x" '{ if(NR == LINE) $COL=VAL } 1' INPUTFILE 
Hello 
World
Hey
Whats Up?

is there any way to reflect this change in the original file?

Look at the post #2 in this thread.

That's not precisely what I suggested. You left out some characters as well as leaving out two important steps.

You never said x was a variable, either. I'll have to change it for that.

awk -v LINE=3 -v COL=1 -v VAL="$x" '{ if(NR == LINE) $COL=VAL } 1' test.txt > /tmp/$$
cat /tmp/$$ > test.txt
rm test.txt

Really though -- is editing-in-place such a good idea? At least test your data somehow before overwriting it.

1 Like