i have a pipe delimited file that looks like this:
123| ste hen| 456| out put
143 | ste hen| 456| out put
i want to delete the spaces--- something like this
123,ste hen,456,out put
143,ste hen,456,out put
this is my code but dont works..
awk '{gsub(/^ | $/,"|"); gsub(/ *, */,"|")}1' test2.txt
CodePudding user response:
awk '{gsub(/ *| */, "|");print}' test2.txt
CodePudding user response:
My very first and fast approach is the next one:
cat testFile.txt | sed 's/|/,/g' | sed 's/\s*,\s*/,/g''
The past command display the following result:
123,ste hen,456,out put
143,ste hen,456,out put
from the following input:
123| ste hen| 456| out put
143 | ste hen| 456| out put
CodePudding user response:
I would use GNU AWK
following way, let file.txt
content be
123| ste hen| 456| out put
143 | ste hen| 456| out put
then
awk '{gsub(/ *\| */,",");print}' file.txt
output
123,ste hen,456,out put
143,ste hen,456,out put
Changes done as compared to {gsub(/^ | $/,"|"); gsub(/ *, */,"|")}1
- eliminated
^
i.e. begin - eliminated
$
i.e. end - escaped
|
as you need literal|
not alternative - looking for zero or more (
*
) spaces around each|
rather than at least 1 at each side - replaced two
gsub
s with single one - trigger printing by
print
rather1
(matter of style, consult style guide of your organization to use solution appropriate in your case)
(tested in gawk 4.2.1)
CodePudding user response:
A sed
solution:
sed 's/^ *//; s/ *$//; s/ *| */,/g' file