1

I am trying to replace string into number from the file So, I have variable &FLOW which need to change to 001, ex :

cat file.txt
This is file ' PISP &FLOW'
PISD.DATA.CYCLE&FLOW..ONE

desired output

This is file ' PISP 001'
PISD.DATA.CYCLE001.ONE

I tried below commands in a script :

for item in file.txt
do
sed 's/\&FLOW/\./001/g' $item
sed 's/\&FLOW/001/g' $item
done

It is giving error. The second sed command is working, but I need to run first the beginning sed command otherwise after running first the second sed command, it would ignore the beginning sed command.

Any help would be appreciated!

flow
  • 63
  • 6
  • What is the first command supposed to do? – JNevill May 30 '19 at 17:33
  • 1
    You set `item` to to literal string `filename`, but the file you show as example input is called `file.txt`, so that won't work, for starters. – Benjamin W. May 30 '19 at 17:34
  • Thank you for reply, I changed into file.txt. It is still not working – flow May 30 '19 at 17:37
  • @JNevill it supposed to change from two dots into one after variable – flow May 30 '19 at 17:39
  • 1
    First of all, you do not need to use two `sed` commands, you may chain them like `sed 's/1/2/g;s/3/4/g'`. However, your patterns are so similar, they only differ in 1 char, so you may make it optional and use a single pattern. More importantly, you did not actually modify file contents, you need to pass the `-i` (inline) option. See [my answer below](https://stackoverflow.com/a/56385601/3832970) with explanations of the pattern and how to use `-i` with both Linux (GNU) and Mac OS (FreeBSD) `sed`. – Wiktor Stribiżew May 30 '19 at 21:14

2 Answers2

1

try this:

for item in file.txt
do
  sed 's/\&FLOW\./001/g' $item
  sed 's/\&FLOW/001/g' $item
done

You had a redundant / in after FLOW

This might also work:

  sed -i 's/\&FLOW[\.]?/001/g' file.txt
Dudi Boy
  • 4,551
  • 1
  • 15
  • 30
  • 1
    Thank you for response! I have a question, what ? is for? – flow May 30 '19 at 22:28
  • `?` is a conditional match for 0 or 1 occurrence of `.` character. If this is correct answer, please mark it as such. – Dudi Boy May 30 '19 at 22:29
  • 2
    `?` is an ERE metachar, it won't work in sed (which uses BREs) unless you add `-E` to enable EREs (GNU sed and OSX/BSD sed which you're probably using for `-i` anyway). Or you can use the POSIX BRE equivalent of `\{0,1\}`. – Ed Morton May 30 '19 at 22:53
1

Use a single sed command and use -i to actually modify the file contents and you need to pass file.txt as the input for the sed command:

sed -i 's/&FLOW\.\{0,1\}/001/g' file.txt

See the online demo. If you are using it in Mac OS, you need sed -i '' 's/&FLOW\.\{0,1\}/001/g' file.txt. Also see sed edit file in place.

Pattern details

It is a POSIX BRE compliant pattern matching

  • &FLOW - a literal &FLOW substring
  • \.\{0,1\} - 0 or 1 occurrence of a . char.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563