Apply Linux command recursively to all files in directory of single (.sh) type - linux

I am trying to apply this command sed -i -e 's/\r$//' to all Shell (.sh) files in my directory I have tried:
sed -i -e -R 's/\r$//' *.sh
But this throws an unknown character error.
Any help would be great cheers!

This is an argument order issue. -e expects the expression/script as the next argument and you are giving it -R.
Swap those two arguments sed -i -e '....'.
That being said the dos2unix program exists for this purpose as well.

Related

sed can't change a file when called in postinstall [duplicate]

Is there an invocation of sed todo in-place editing without backups that works both on Linux and Mac? While the BSD sed shipped with OS X seems to need sed -i '' …, the GNU sed Linux distributions usually come with interprets the quotes as empty input file name (instead of the backup extension), and needs sed -i … instead.
Is there any command line syntax which works with both flavors, so I can use the same script on both systems?
If you really want to just use sed -i the 'easy' way, the following DOES work on both GNU and BSD/Mac sed:
sed -i.bak 's/foo/bar/' filename
Note the lack of space and the dot.
Proof:
# GNU sed
% sed --version | head -1
GNU sed version 4.2.1
% echo 'foo' > file
% sed -i.bak 's/foo/bar/' ./file
% ls
file file.bak
% cat ./file
bar
# BSD sed
% sed --version 2>&1 | head -1
sed: illegal option -- -
% echo 'foo' > file
% sed -i.bak 's/foo/bar/' ./file
% ls
file file.bak
% cat ./file
bar
Obviously you could then just delete the .bak files.
This works with GNU sed, but not on OS X:
sed -i -e 's/foo/bar/' target.file
sed -i'' -e 's/foo/bar/' target.file
This works on OS X, but not with GNU sed:
sed -i '' -e 's/foo/bar/' target.file
On OS X you
can't use sed -i -e since the extension of the backup file would be set to -e
can't use sed -i'' -e for the same reasons—it needs a space between -i and ''.
When on OSX, I always install GNU sed version via Homebrew, to avoid problems in scripts, because most scripts were written for GNU sed versions.
brew install gnu-sed --with-default-names
Then your BSD sed will be replaced by GNU sed.
Alternatively, you can install without default-names, but then:
Change your PATH as instructed after installing gnu-sed
Do check in your scripts to chose between gsed or sed depending on your system
As Noufal Ibrahim asks, why can't you use Perl? Any Mac will have Perl, and there are very few Linux or BSD distributions that don't include some version of Perl in the base system. One of the only environments that might actually lack Perl would be BusyBox (which works like GNU/Linux for -i, except that no backup extension can be specified).
As ismail recommends,
Since perl is available everywhere I just do perl -pi -e s,foo,bar,g target.file
and this seems like a better solution in almost any case than scripts, aliases, or other workarounds to deal with the fundamental incompatibility of sed -i between GNU/Linux and BSD/Mac.
Answer: No.
The originally accepted answer actually doesn't do what is requested (as noted in the comments). (I found this answer when looking for the reason a file-e was appearing "randomly" in my directories.)
There is apparently no way of getting sed -i to work consistently on both MacOS and Linuces.
My recommendation, for what it is worth, is not to update-in-place with sed (which has complex failure modes), but to generate new files and rename them afterwards. In other words: avoid -i.
There is no way to have it working.
One way is to use a temporary file like:
TMP_FILE=`mktemp /tmp/config.XXXXXXXXXX`
sed -e "s/abc/def/" some/file > $TMP_FILE
mv $TMP_FILE some/file
This works on both
Here's another version that works on Linux and macOS without using eval and without having to delete backup files. It uses Bash arrays for storing the sed parameters, which is cleaner than using eval:
# Default case for Linux sed, just use "-i"
sedi=(-i)
case "$(uname)" in
# For macOS, use two parameters
Darwin*) sedi=(-i "")
esac
# Expand the parameters in the actual call to "sed"
sed "${sedi[#]}" -e 's/foo/bar/' target.file
This does not create a backup file, neither a file with appended quotes.
The -i option is not part of POSIX Sed. A more portable method would be
to use Vim in Ex mode:
ex -sc '%s/alfa/bravo/|x' file
% select all lines
s replace
x save and close
Steve Powell's answer is quite correct, consulting the MAN page for sed on OSX and Linux (Ubuntu 12.04) highlights the in-compatibility within 'in-place' sed usage across the two operating systems.
JFYI, there should be no space between the -i and any quotes (which denote an empty file extension) using the Linux version of sed, thus
sed Linux Man Page
#Linux
sed -i""
and
sed OSX Man page
#OSX (notice the space after the '-i' argument)
sed -i ""
I got round this in a script by using an alias'd command and the OS-name output of 'uname' within a bash 'if'. Trying to store OS-dependant command strings in variables was hit and miss when interpreting the quotes. The use of 'shopt -s expand_aliases' is necessary in order to expand/use the aliases defined within your script. shopt's usage is dealt with here.
Portable script for both GNU systems and OSX:
if [[ $(uname) == "Darwin" ]]; then
SP=" " # Needed for portability with sed
fi
sed -i${SP}'' -e "s/foo/bar/g" -e "s/ping/pong/g" foobar.txt
I ran into this problem. The only quick solution was to replace the sed in mac to the gnu version:
brew install gnu-sed
If you need to do sed in-place in a bash script, and you do NOT want the in-place to result with .bkp files, and you have a way to detect the os (say, using ostype.sh), -- then the following hack with the bash shell built-in eval should work:
OSTYPE="$(bash ostype.sh)"
cat > myfile.txt <<"EOF"
1111
2222
EOF
if [ "$OSTYPE" == "osx" ]; then
ISED='-i ""'
else # $OSTYPE == linux64
ISED='-i""'
fi
eval sed $ISED 's/2222/bbbb/g' myfile.txt
ls
# GNU and OSX: still only myfile.txt there
cat myfile.txt
# GNU and OSX: both print:
# 1111
# bbbb
# NOTE:
# if you just use `sed $ISED 's/2222/bbbb/g' myfile.txt` without `eval`,
# then you will get a backup file with quotations in the file name,
# - that is, `myfile.txt""`
The problem is that sed is a stream editor, therefore in-place editing is a non-POSIX extension and everybody may implement it differently. That means for in-place editing you should use ed for best portability. E.g.
ed -s foobar.txt <<<$',s/foo/bar/g\nw'
Also see https://wiki.bash-hackers.org/howto/edit-ed.
You can use sponge. Sponge is an old unix program, found in moreutils package (both in ubuntu and probably debian, and in homebrew in mac).
It will buffer all the content from the pipe, wait until the pipe is close (probably meaning that the input file is already close) and then overwrite:
From the man page:
Synopsis
sed '...' file | grep '...' | sponge file
The following works for me on Linux and OS X:
sed -i' ' <expr> <file>
e.g. for a file f containing aaabbaaba
sed -i' ' 's/b/c/g' f
yields aaaccaaca on both Linux and Mac. Note there is a quoted string containing a space, with no space between the -i and the string. Single or double quotes both work.
On Linux I am using bash version 4.3.11 under Ubuntu 14.04.4 and on the Mac version 3.2.57 under OS X 10.11.4 El Capitan (Darwin 15.4.0).

Using sed in a script

I am trying to insert a line of text under a line of existing text in a file as per the following excerpt:
#!/bin/bash
MATCH='Text_To_Look_For'
INSERT='Text_To_Add'
FILE='/home/user/test.txt'
echo "Modifying file..."
sed -i 's/"$MATCH/$MATCH"\n"$INSERT"/' $FILE
echo "Done."
I have tried all sorts of combinations of / ' and " but cant seem to make it work. The script will run now but not insert anything. In other formats I keep getting errors relating to:
unterminated s command
sed: -e expression #1, char 35: unknown option to `s'
You didn't say what version of sed you're using, I've seen something similar on MacOS, where the standard sed is rather poor... Worked around by installing a GNU Sed (invoked later as gsed).
Anyway, can you give a try with sed a command (which stands for append):
#!/bin/bash
MATCH='Text_To_Look_For'
INSERT='Text_To_Add'
FILE='/tmp/xxx'
echo "Modifying file..."
sed -i "/$MATCH/a $INSERT" $FILE
echo "Done."
Best regards,
Jarek
The -i option to sed should be followed by a file extension, see man sed: -i extension - Edit files in-place, saving backups with the specified extension.
It is trying to use your s command as a filename extension!
Try this:
sed -i .bak s/$MATCH/$MATCH\n$INSERT/ "$FILE"
Note that the -i option is non-standard and sed versions vary. For example you might have to remove the space:
sed -i.bak s/$MATCH/$MATCH\n$INSERT/ "$FILE"
An alternative to the -i is:
if sed s/$MATCH/$MATCH\n$INSERT/ "$FILE" > "$FILE.bak"
then
mv "$FILE.bak" "$FILE"
fi

linux shell sed command

I have file sedFile.txt which has string in format CONNECTION='mysql://user:user#10.79.19.2:3308/SSMS/SUBSCRIBE';
I created one script which has following lines:
fin=CONNECTION='mysql://user:user#10.79.19.2:3308/SSMS/SUBSCRIBE';
repla=connection
sed -i "s/\$fin/$repla/g" /home/sedFile.txt
Even though the script is running, it's not doing changes in my file.
I tried following:
sed -i 's/${fin}/${repla}/g' /home/sedFile.txt
sed -i 's/^$fin/$repla/g' /home/sedFile.txt
sed -i "s/$fin/$repla/g" /home/sedFile.txt
sed -i "s/${fin}/${repla}/g" /home/sedFile.txt
If you want the single quotes to be included in the pattern you have to quote or escape them:
fin="CONNECTION='mysql://user:user#10.79.19.2:3308/SSMS/SUBSCRIBE'"
then, use any of the four lines you tried (i.e. not the one with \$fin).
Update: In order to make sed work, you cannot use / to separate the pattern and the substitution, because this character exists in the string already. Use a different separator:
sed -i "s,$fin,$repla,g" /home/sedFile.txt
Might be the same as the other answers, but I doesn't hurt to try
fin="CONNECTION='mysql://user:user#10.79.19.2:3308/SSMS/SUBSCRIBE';"
repla="connection"
sed -i "s|${fin}|${repla}|g" /home/sedFile.txt
fin="CONNECTION='mysql://user:user#10.79.19.2:3308/SSMS/SUBSCRIBE'"
repla=connection
in=$fin out=$repla perl -pi.nk -e 's/\Q$ENV{"in"}/$ENV{"out"}/g' /home/sedFile.txt

What is the command to delete empty lines in a file using sed?

What is the sed command to delete empty lines in a file.
What is the command (sed command?) to delete empty files in a folder?
You have to 'd' which is used to delete.
Ex:
sed -i '/^$/d' test
-i - is used to affect the file.
^ - is a beginning of line
$ - is a end of line
d - delete if there is a empty line
I hope this will help you.
/^$/d should do it.
for example
sed -i -e "/^$/d" myfile.txt
if you want to do this to all the files in a folder:
sed -i -e "/^$/d" *
-i means "edit in place" without it, the file will be edited and sent to standard output. The original file will be unmodified.
sed -e 's/#.*//;/^\s*$/d' /etc/lvm/lvm.conf

`sed` works, but `sed -i` returns an error

This line works:
sed -r -e 's/^([^#a-z]+)localhost/\1hostname.domain hostname localhost/' /etc/hosts
But adding the itty option "i":
sed -ir -e 's/^([^#a-z]+)localhost/\1hostname.domain hostname localhost/' /etc/hosts
Results in:
sed: -e expression #1, char 60: invalid reference \1 on `s' command's RHS
Can someone tell me what's going on??
You've turned off the -r (extended syntax) option, because what you append to -i isn't more options, but an optional backup suffix. From the manpage:
-i[SUFFIX], --in-place[=SUFFIX]
edit files in place (makes backup if extension supplied)
So just separate them:
sed -i -r -e 's/^([^#a-z]+)localhost/\1hostname.domain hostname localhost/' /etc/hosts
I think you should separate options: write -i -r and not -ir, since -i may interpret r as the suffix to append to the old unedited file, so that -r is not taken
"-ir" means something different from "-i -r" or "-ri", see the man page.

Resources