Wednesday, April 27, 2022

[SOLVED] Bash command runs from command line but not from within a script

Issue

Under WSL (Ubuntu), I use this command to extract the From: line from a folder of .eml files:

for f in *.eml; do echo -oe | grep "^From" < "$f" | sed -e "s/From://g" >> emails.txt; done

Works great. However, if I put that same command in a bash script, it fails with this message:

/bin/bash: for f in *.eml; do echo -oe | grep "^From" < "$f" | sed -e "s/From://g" >> emails.txt; done: No such file or directory

Please tell me why. Thanks.

Edit: Below is the script, which resides in home/jim/bin (which is in the path) and is run from the directory containing the .eml files.

#!/bin/bash
for f in *.eml; do echo -oe | grep "^From" < "$f" | sed -e "s/From://g" >> emails.txt; done

Solution

There's no need for the loop. You can simply give all the filenames to sed

#!/bin/bash
sed -n '/^From:/s/^From: //p' *.eml >> emails.txt


Answered By - Barmar
Answer Checked By - Clifford M. (WPSolving Volunteer)