Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.6k views
in Technique[技术] by (71.8m points)

windows - Replace First Occurrence Only of Pipe Character in String

I need to remove an extra pipe character at the end of header row of a pipe delimited csv file with sed. The literal string that I am trying to find is COLNAME|

Working on a GCP Windows server. The command I am trying to use:

"C:Program Files (x86)GnuWin32insed.exe" sed '0,/COLNAME"|"/s//COLNAME/' FILENAME

returns the output... sed.exe: -e expression #1, char 3: unterminated `s' command

I'm new to sed and have been playing around with the s command for a while but cannot seem to get the syntax correct.

Any suggestion on how to accomplish this?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you want to replace COLNAME| with COLNAME"|" in Windows, using the GNU sed, you can use

"C:Program Files (x86)GnuWin32insed.exe" "s/COLNAME|/COLNAME"^""|"^""/g"

Here, COLNAME| matches COLNAME| and COLNAME"^""|"^"" forms the literal COLNAME"|" replacement since COLNAME" ends the quoted string, ^" appends a literal " char to the sed command, "|" appends a | char to the sed command and then ^" appends another literal " to the sed command, and the next " starts the finishing part. The g flag makes it match and replace all occurrences.

If you want to replace COLNAME"|" with COLNAME in Windows, using the GNU sed, you can do that with

"C:Program Files (x86)GnuWin32insed.exe" "s/COLNAME"^""|"^""/COLNAME/g" FILENAME
"C:Program Files (x86)GnuWin32insed.exe" "s/COLNAMEx22|x22/COLNAME/g" FILENAME
"C:Program Files (x86)GnuWin32insed.exe" "s/COLNAMEd34|d34/COLNAME/g" FILENAME

Mind that you need to enclose the substitution command with double quotes and to match a double quote, you can't simply use a " or a ", you can match it with an escaped ^", or with x22, a hex reprentation of the char, or d34.

Note that in "s/COLNAME"^""|"^""/COLNAME/g", the sed command is built in the following way:

  1. "s/COLNAME" sets the beginning
  2. ^" appends a literal " char to the sed command
  3. "|" - adds | pipe char
  4. ^" - adds another "
  5. "/COLNAME/g" - finishes off the sed command with the replacement and the global modifier/flag.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...