2

I have a requirement to replace a specific column value (identified by location) with another value on a pipe-delimited file at specific row.

sample file:

a|abc|val|sum|temp
bs|run|win|can|done
jump|over|change|value

Now, I want to replace the value on row2 at column3 with "changed".  (In the above example input, the old, to-be-replaced value is "win", but it can be anything, and I won't know in advance what it is.)

expected output:

a|abc|val|sum|temp
bs|run|changed|can|done
jump|over|change|value

3

In GNU sed,

sed -E '2s/^(([^|]*\|){2})[^|]*/\1changed/' input
  • The first “2” (2s) identifies the line number.
  • The second “2” ({2}) identifies how many columns to skip over and leave the same.  If you wanted to change the 17th field, you would use {16}.
  • This command will write the modified file to the standard output.  You should probably run it with output to the terminal first to verify that it is what you want.  Then, if you want, you can run the command with output to a second file, and then move or copy that file over the input file.
  • Alternatively, you can add the -i option to sed to get it to overwrite the input file.

In awk:

awk -F'|' -vOFS='|' 'NR==2 {$3 = "changed"} {print}' input
  • This command will write the modified file to the standard output.  You should probably run it with output to the terminal first to verify that it is what you want.  Then, if you want, you can run the command with output to a second file, and then move or copy that file over the input file.
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.