1829187 Members
10897 Online
109986 Solutions
New Discussion

File Content replacement

 
SOLVED
Go to solution
Pando
Regular Advisor

File Content replacement

I have a file with the following line content..

...
...
...
SFC_ID,
...
...

I need a command or a perl command to add a "" after the SFC_ID, line.

Maximum points for all correct!
7 REPLIES 7
Hein van den Heuvel
Honored Contributor

Re: File Content replacement

$ cat > x
...
SFC_ID,
...
$ perl -pe 's/(^SFC_ID,$)/\1""/' x
...
SFC_ID,""
...



I use the (xxx) ... \1 construction to allow you to replace it with more elaborate match strings and append "" to whatever matches.
For example: 's/(^\w+_ID,$)/\1""/'
This will append to any line with an _ID token, including SFC_ID.

- the () remebers into \1
- the ^ forces to start looking at Begin of line
- the $ forces the line to end right there.

sprinkle with \s* and remove anchors as required.

Cheers,
Hein.


G. Vrijhoeven
Honored Contributor

Re: File Content replacement

Hi,

cat file | sed 's/SFC_ID,/SFC_ID,\"\"/' > file1
mv file1 file

Regards,

Gideon
( who is not sure about the \"\" part)
Pando
Regular Advisor

Re: File Content replacement

Hello Hein,

Thanks for the solution. I've tested it but when i open the file, there is no "" character strings after the SFC_ID, line.
Hein van den Heuvel
Honored Contributor

Re: File Content replacement


Well... it worked for me.
Apparently your actual datafile does not match what you included in the topic, and what I describe in the explanation for the match.
There might be trailing spaces. If you want to retain those before the "" then try:

$ perl -pe 's/(^SFC_ID,\s*$)/\1""/' x

or after:

$ perl -pe 's/(^SFC_ID,)/\1""/' x


or gone:

$ perl -pe 's/(^SFC_ID,)\s*$/\1""/' x

Untested!

If it still does not work, then please attach a text file with soem actual sample data.

And... try to read up on 'regular expressions' "a gift for life"

\s is 'whitespace such as blank or tab'
\s* is 'zero or more whitespaces'

Cheers,
Hein.
Pando
Regular Advisor

Re: File Content replacement

Hello Hein,

Please see attached file.
Hein van den Heuvel
Honored Contributor
Solution

Re: File Content replacement

Well, it works fine over here.
I just saved your attachment to my pc.
Tossed it over to a drive on a (tru64) unix box as tmp.dat and it gives:

# grep SFC tmp.dat
SFC_ID,

# perl -pe 's/(^SFC_ID,$)/\1""/' tmp.dat | grep SFC
SFC_ID,""

Removing the anchors also works, but migh latch on to replacements you did not intent:

# perl -pe 's/(SFC_ID,)/\1""/' tmp.dat | grep SFC
SFC_ID,""

Hein
Pando
Regular Advisor

Re: File Content replacement

Thanks for all the replies.