替换'>'在shell / bash中的几个文件中使用'> \ n'

时间:2018-02-12 20:20:10

标签: bash shell unix sed tr

我在一个文件夹中有多个文件,我想在所有这些文件中的>替换>\n个字符。

但无论我做什么,\n字符都不会在>字符后添加。

我尝试了以下内容:

echo '>ABCCHACAC' | tr '\>' '>\\n'
echo '>ABCCHACAC' | tr '>' '>\\n'
echo '>ABCCHACAC' | tr '>' '>\n'
echo '>ABCCHACAC' | tr '>' '\>\n'
echo '>ABCCHACAC' | tr '>' '\>\\n'
echo '>ABCCHACAC' | tr '>' '\>\\n'

但是我输出的输入字符串与输出相同,而我想要的正确输出是:

>
ABCCHACAC

我正在使用这个脚本在许多文件上做同样的事情:

for f in *.txt
do
  tr ">" ">\n" < "$f" > $(basename "$f" .txt)_newline_added.txt
done

2 个答案:

答案 0 :(得分:3)

tr用于一对一字符替换,而不是替换字符串。例如。如果您使用abc翻译def,则会将所有a替换为d,将所有b替换为e,并将所有c替换为ftr '>' '>\n'。当第二个字符串比第一个字符串长时,将忽略额外的字符。因此>表示将>替换为\n并忽略sed

使用sed 's/>/>\n/g' "$f" > "$(basename "$f" .txt)_newline_added.txt" 执行字符串替换。

SELECT Products.ProductID, SUM([Quantity] * [Price]) AS Total_Order_Value 
FROM OrderDetails
INNER JOIN Products ON OrderDetails.ProductID=Products.ProductID
GROUP BY Products.ProductID
ORDER BY Products.ProductID DESC

答案 1 :(得分:0)

除了Barmar的回答,如果您使用基于BSD的* nix(例如OS X),您需要包含转义的文字换行符,或者可能使用{{ 1}}除了tr

Escaped文字换行符:

sed

$ sed 's/^>/>\ /' "$f" sed

tr

Insert newline (\n) using sed