I need to replace specific field (x) in a table with new value (y):
Input:
1 2 3 4
5 x 6 7
8 9 0 0
Output:
1 2 3 4
5 y 6 7
8 9 0 0
I have no idea how to do this.
I need to replace specific field (x) in a table with new value (y):
Input:
1 2 3 4
5 x 6 7
8 9 0 0
Output:
1 2 3 4
5 y 6 7
8 9 0 0
I have no idea how to do this.
replace all x into y?
or only in 2nd line?
or in lines that match some pattern? e.g. starts with 5?
the codes below change any x-fields to y only in the 2nd line.
awk '{if (NR==2)for(i=1;i<=NF;i++) $i=($i=="x")?"y":$i; print $0}' input
This does it all. Remove parts to do one or the other.
awk '/^5/||(NR==2){for(i=1;i<=NF;i++)if($i=="x")$i="y";print $0};/^[^5]/&&(NR!=2)' input
awk 'NR==2 {sub(" x ", " y ")}1' input
or with sed
sed '2s/ x / y /' input
Thanks, it works.
But I have set of data and in every file instead of "x" is different number. I need to clear this field and after that fill with new value for example 100 (for all data sets).
data 1
0 0 0 0
0 3 0 0
0 0 0 0
data 2
0 0 0 0
0 1 0 0
0 0 0 0
data 3
0 0 0 0
0 8 0 0
0 0 0 0
output
0 0 0 0
0 100 0 0
0 0 0 0
Is the value you want to replace always the second value in the second row? Or is it the only nonzero value in the file? Do the files only have 3 rows?
I want to replace always second value in second row.
My real input data has thousands of rows and about 20 columns with different numbers. In every file I want to replace value in specific field (for example second row, second column).
awk -v row=2 -v col=2 'FNR==1{print FILENAME} FNR==row{$col="100"}1' datafile*
You can specify the row and col where you want to make change.
awk '{if (NR==2) $2=100; print $0}' input
this handles "only the 2nd column/field in 2nd line"
It works!
Thank You.
awk '{if(NR==2)$2=100;print $0}' input
---------- Post updated at 10:17 AM ---------- Previous update was at 10:16 AM ----------
Type 'man awk' and 'man bash' at the command line for complete documentation.