How do I replace a string with a newline using a b

2019-03-25 05:56发布

I have the following input:

Value1|Value2|Value3|Value4@@ Value5|Value6|Value7|Value8@@ Value9|etc...

In my bash script I would like to replace the @@ with a newline. I have tried various things with sed but I'm not having any luck:

line=$(echo ${x} | sed -e $'s/@@ /\\\n/g')

Ultimately I need to parse this whole input into rows and values. Maybe I am going about it wrong. I was planning to replace the @@ with newlines and then loop through the input with setting IFS='|' to split up the values. If there is a better way please tell me, I am still a beginner with shell scripting.

7条回答
对你真心纯属浪费
2楼-- · 2019-03-25 06:10

Using pure BASH string manipulation:

eol=$'\n'
line="${line//@@ /$eol}"

echo "$line"
Value1|Value2|Value3|Value4
Value5|Value6|Value7|Value8
Value9|etc...
查看更多
Emotional °昔
3楼-- · 2019-03-25 06:10

How about:

for line in `echo $longline | sed 's/@@/\n/g'` ; do
    $operation1 $line
    $operation2 $line
    ...
    $operationN $line
    for field in `echo $each | sed 's/|/\n/g'` ; do
        $operationF1 $field
        $operationF2 $field
        ...
        $operationFN $field
    done
done
查看更多
我只想做你的唯一
4楼-- · 2019-03-25 06:13

This will work

sed 's/@@ /\n/g' filename

replaces @@ with new line

查看更多
Anthone
5楼-- · 2019-03-25 06:18

Finally got it working with:

sed 's/@@ /'\\\n'/g'

Adding the single quotes around \\n seemed to help for whatever reason

查看更多
祖国的老花朵
6楼-- · 2019-03-25 06:29

I recommend using the tr function

echo "$line" | tr '@@' '\n'

For example:

[itzhaki@local ~]$ X="Value1|Value2|Value3|Value4@@ Value5|Value6|Value7|Value8@@"
[itzhaki@local ~]$ X=`echo "$X" | tr '@@' '\n'`
[itzhaki@local ~]$ echo "$X"
Value1|Value2|Value3|Value4

 Value5|Value6|Value7|Value8
查看更多
Evening l夕情丶
7楼-- · 2019-03-25 06:31

If you don't mind to use perl:

echo $line | perl -pe 's/@@/\n/g'
Value1|Value2|Value3|Value4
 Value5|Value6|Value7|Value8
 Value9|etc
查看更多
登录 后发表回答