'Keep new line where grep is output
When I run ls I see the following. I want to delete all instances of 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' returns only the screenshot entries each on a new line
The following code tries to find the file screen then shot for $i
for i in $(ls | grep -F "Screen Shot"); do rm $i; done
and fails because it uses a space as delimiter
I also observed that grep will print new lines when stdout is the terminal but when I redirect to a file, the new lines are maintained
(ls | grep -F "Screen Shot") > shots.txt
However, if I set the output to a variable there are no new lines
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
- How do I iterate over the screenshot entries and delete them?
- How do I keep a newline on grep?
EDIT: Cyrus (see comment) has working answers to question 1. Still looking for question 2 answers for grep behavior
Solution 1:[1]
You can still do this, you just need to specify the IFS (internal field separator).
shots="$(ls | grep -F "Screen Shot")"
echo $shots
>some_long_one_line_blob
IFS='$\n'
echo $shots
>line
>by
>line
>output
Or can you the -E argument to echo which will evaluate the newline characters.
echo -E "$shots"
>line
>by
>line
>output
Solution 2:[2]
This was the right answer for me:
grep_result=`grep $pattern $searchfile`
echo "$grep_result"
produced the right echo output (cr-separated) when the $pattern was spread across multiple lines.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | cidjen |
