0

I have file that looks like this :

1,2,3,4
5,6,7,8

I want to substitute 2rd column containing 6 to 89. The desired output is

1,2,3,4
5,89,7,8

But if I type

index=2
cat file | sed 's/[^,]*/89/'$index

I get

1,89,3,4
5,89,7,8

and if I type

index=2
cat file | sed 's/[^,]6/89/'$index

nothing changes. Why is it like this? How can I fix this? Thank you.

wkde
  • 453
  • 3
  • 13
  • 1
    `[^,]` matches a single character which is not comma (or newline). It is unclear what you imagine it should match. – tripleee Nov 13 '18 at 04:59
  • Possible duplicate of [How to replace second column of csv file with a specific value "XYX"](https://stackoverflow.com/questions/15745250/how-to-replace-second-column-of-csv-file-with-a-specific-value-xyx) – tripleee Nov 13 '18 at 04:59
  • 1
    Also, the [`cat` is useless.](/q/11710552) – tripleee Nov 13 '18 at 05:01
  • 1
    Possible duplicate of https://stackoverflow.com/questions/49833671/sed-replace-nth-column-of-multiple-tsv-files-without-header – tripleee Nov 13 '18 at 05:05
  • Yes I did not know what [^,] means. Thank you! I don't need to substitute all lines – wkde Nov 13 '18 at 06:02

2 Answers2

2

Since you want to change the second column containing a 6 and you have a comma as field separator it is actually very easy with sed:

sed 's/^\([^,]*\),6,/\1,89,/`

Here we make use of back-referencing to remember the first column.

If you want to replace the 6 in the 5th column, you can do something like:

sed 's/^\(\([^,]*,\)\{4\}\)6,/\189,/'

It is, however, much more comfortable using awk:

awk 'BEGIN{FS=OFS=","}($2==6){$2=89}1'
kvantour
  • 25,269
  • 4
  • 47
  • 72
0

I solved this by using awk

awk 'BEGIN{FS=OFS=","} {if ($2==6) $2=89}1' file >file1
wkde
  • 453
  • 3
  • 13