I'm working on a bash script for partially automating router connection in command line. I'm a newbie in Bash. This is part where I have a problem:#!/bin/bashSTRING2=ESSIDMYPWD=$(pwd)sudo iwlist wlan1 scan | grep $STRING2 | grep -n $STRING2 > $STRING2.txtsed -r -e 's/\s+//g' -e 's/:ESSID//' $MYPWD/$STRING2.txtThe last line opens a text file, then deletes white spaces and also :ESSID's from the text file which is $MYPWD/$STRING2.txt. What I want to do is also write the output of sed to that file by piping. A previous approach was piping grep : > $MYPWD/$STRING2.txt at the end such as :sed -r -e 's/\s+//g' -e 's/:ESSID//' $MYPWD/$STRING2.txt | grep : > $MYPWD/$STRING2.txtBut it ended up with an empty $MYPWD/$STRING2.txt. I'm not sure why this is happening. Any ideas?EditWithout the last piped grep, text file contains some text like this after execution:1:___________ESSID:somessid2:___________ESSID:somessid3:___________ESSID:somessid4:___________ESSID:somessidps: <__> stands for white space#!/bin/bash#declaring a string variableSTRING=MERHABA DUNYASTRING2=ESSIDCOUNTER=1MYPWD=$(pwd)echo -e Later you can check the recent networks around you from :  $MYPWD/$STRING2.txt\n#or MYPWD=${pwd}#-e flag enables \n escapeecho -e $STRING2.txt is being updated\n. . .\nsudo iwlist wlan1 scan | grep $STRING2 | grep -n $STRING2 > $STRING2.txt # | sed -i# #s/ //g $STRING2.txt > $STRING2.txtsed -r -e 's/\s+//g' -e 's/:ESSID//' $MYPWD/$STRING2.txtNUMLINE=$(sudo cat $MYPWD/$STRING2.txt | wc -l)echo -e \n. . .echo -e \nThere are $NUMLINE  visible networks\n
Bash : rewriting a file which is read in same line
bash;sed;pipe
When you have a command such as thissed -e ... datafile >datafileYou will end up with a zero length result. The reason is that the shell sets up stdin and stdout before it executes the command. So stdout is sent to the file datafile, creating or truncating it in the process, and only then is the sed -e ... datafile run.A common solution is something like thissed -e ... datafile >datafile.tmp && mv -f datafile.tmp datafileSome commands (including versions of sed) have the edit in place option:sed -i.bak -e ... datafilesed --in-place=.bak -e ... datafile