0

I am using sed command make substitution in the file. Assume my file1 is:

10
11
10
11

Then I want to substitute the 1st "10" in file1 to "12", and dump to file2. The file2 should be:

12
11
10
11

I tried this command:

sed 's/10/12/' file1 >file2

But it changed the 2nd "10" also. So, how can I write the sed command to do that?

Jianli Cheng
  • 371
  • 1
  • 8
  • 17

4 Answers4

1

If you can use awk instead of sed, you can have more control like this:

awk '!changed && /10/ { sub(/10/, "12"); changed = 1}1' file1
12
11
10
11
1

try:

sed '0,/10/s/10/12/' file1 >file2
GriffinG
  • 662
  • 4
  • 13
1

Like GriffinG said, you can do something like this:

sed '0,/10/ s/10/12/' file1 > file2

The 0,/10/ at the beginning sets the bounds on the following substitution command. It says start from line 0 (the first line), and go until a line it matches the pattern /10/. So After that first match, sed will stop processing that substitution.

Dan Fego
  • 13,644
  • 6
  • 48
  • 59
1

If you do not have GNU sed, try:

echo | cat - file | sed '1,/10/s/10/12/; 1d'

or

sed '1,/10/s/10/12/; 1d' << EOF

$(cat file)
EOF

or in bash / ksh93

sed '1,/10/s/10/12/; 1d' <(echo; cat file)

GNU sed knows 0,/10/ so the extra empty line is not required

Scrutinizer
  • 9,608
  • 1
  • 21
  • 22