Reputation: 1178
I have a file in which i have many spaces between the columns. I want to replace those spaces with | character but only once.
I tried like this sed -e "s/ /|/g"
but it relacing evry space with | character.
My file contains
Col1 Col2 Col3
A B C
D E F
Actually i am fetching data from db2 using script and the output comming like this. I need to put a delimeter between the columns so that i can compare those data later.
I want output like this
Col1|Col2|Col3
A|B|C
D|E|F
How can i resolve this. Pls help
Upvotes: 0
Views: 101
Reputation: 1178
I have solved the above problem by using this
sed -e 's/[ ]\{1,\}/|/g'
Upvotes: 0
Reputation: 58400
This might work for you (GNU sed):
sed -r 's/^\s+//;s/\s+/|/g' file
Remove leading whitespace and replace all other whitespace by |
Upvotes: 0
Reputation: 785128
An awk
with OFS='|'
would be simpler here:
awk -v OFS='|' '{$1=$1} 1' file
Col1|Col2|Col3
A|B|C
D|E|F
{$1=$1}
is a way to tell that each record has changed thus it ends up using OFS
as delimiter for rewriting records.
Upvotes: 1
Reputation: 6478
Match a column with space around, ignore if it is the last column.
sed -e "s/(?! *(\w+) *$)( *(\w+) *)/$2|/gm"
( *(\w+) *)
match a word with spaces arround (greedy)?! *(\w+) *$)
Positive lookahead, ignore match that does end the line$2|
replace by the word followed by your delimiterActually i am fetching data from db2 using script and the output comming like this.
You might have tabs (\t
) instead of spaces, its a common separator for "csv" exports. Also, if you can modify your script you can specify a delimiter for the export.
Upvotes: 1
Reputation: 10039
Replace multispace between data, but not for the header nor trailer space
sed -e ':redo' -e 's/\([^[:blank:]]\)[[:blank:]]\{1,\}\([^[:blank:]]\)/\1|\2/g;t redo'
Due to sed behavior(excluding already taken pattern in a g
option), 2 pass are needed with this posix compliant version
Upvotes: 0