保持输出grep的新行

时间:2017-11-21 20:40:19

标签: linux for-loop grep

当我运行ls时,我看到以下内容。我想删除Screen Shot..

的所有实例
10-15
BashStorage
blah.csv
LockScreen.app
NetsuiteBFN
Screen Shot 2017-10-26 at 11.09.08 AM.png
Screen Shot 2017-11-02 at 12.24.13 PM.png
Screen Shot 2017-11-10 at 9.20.33 AM.png
Screen Shot 2017-11-10 at 9.21.29 AM.png
Screen Shot 2017-11-20 at 10.26.24 AM.png
Screen Shot 2017-11-20 at 10.29.18 AM.png
Screen Shot 2017-11-20 at 10.30.40 AM.png
Screen Shot 2017-11-20 at 10.31.55 AM.png
Screen Shot 2017-11-20 at 10.34.11 AM.png
Screen Shot 2017-11-20 at 10.55.34 AM.png
Screen Shot 2017-11-20 at 10.56.44 AM.png
Screen Shot 2017-11-20 at 10.56.54 AM.png
Screen Shot 2017-11-20 at 10.59.20 AM.png
finalResourceUrls.txt
good
lockScreen
lockScreen.zip
ls.txt
x

ls | grep -F 'Screen Shot'仅返回新行

上的屏幕截图条目

以下代码尝试为screen找到文件shot,然后$i for i in $(ls | grep -F "Screen Shot"); do rm $i; done

并失败,因为它使用space作为分隔符

我还观察到当stdout是终端时grep将打印新行,但是当我重定向到文件时,新行会被维护 (ls | grep -F "Screen Shot") > shots.txt

但是,如果我将输出设置为变量,则没有新行

shots="$(ls | grep -F "Screen Shot")"

Screen Shot 2017-10-26 at 11.09.08 AM.png Screen Shot 2017-11-02 at 12.24.13 PM.png Screen Shot 2017-11-10 at 9.20.33 AM.png Screen Shot 2017-11-10 at 9.21.29 AM.png Screen Shot 2017-11-20 at 10.26.24 AM.png Screen Shot 2017-11-20 at 10.30.40 AM.png Screen Shot 2017-11-20 at 10.31.55 AM.png Screen Shot 2017-11-20 at 7.01.32 PM.png Screen Shot 2017-11-21 at 11.49.15 AM.png
  1. 如何迭代屏幕截图条目并将其删除?
  2. 如何在grep上保留换行符?
  3. 编辑:Cyrus(见评论)对问题1有工作答案。仍在寻找问题2的grep行为答案

1 个答案:

答案 0 :(得分:1)

您仍然可以执行此操作,只需指定IFS(内部字段分隔符)。

shots="$(ls | grep -F "Screen Shot")"
echo $shots
>some_long_one_line_blob

IFS='$\n'
echo $shots
>line
>by
>line
>output

或者你可以使用-E参数来回显评估换行符。

echo -E "$shots"
>line
>by
>line
>output