How to Convert a Text/Plain to Text/X.Shellscript

Open and write data to text file using Bash?

The short answer:

echo "some data for the file" >> fileName

However, echo doesn't deal with end of line characters (EOFs) in an ideal way. So, if you're going to append more than one line, do it with printf:

printf "some data for the file\nAnd a new line" >> fileName

The >> and > operators are very useful for redirecting output of commands, they work with multiple other bash commands.

Find and Replace Inside a Text File from a Bash Command

The easiest way is to use sed (or perl):

sed -i -e 's/abc/XYZ/g' /tmp/file.txt

Which will invoke sed to do an in-place edit due to the -i option. This can be called from bash.

If you really really want to use just bash, then the following can work:

while IFS='' read -r a; do
echo "${a//abc/XYZ}"
done < /tmp/file.txt > /tmp/file.txt.t
mv /tmp/file.txt{.t,}

This loops over each line, doing a substitution, and writing to a temporary file (don't want to clobber the input). The move at the end just moves temporary to the original name. (For robustness and security, the temporary file name should not be static or predictable, but let's not go there.)

For Mac users:

sed -i '' 's/abc/XYZ/g' /tmp/file.txt

(See the comment below why)

Proper mime-type of shell scripts in subversion

The file utility uses `text/x-shellscript' for shell scripts:

$ file --mime-type /tmp/test.sh
/tmp/test.sh: text/x-shellscript

Get specific line from text file using just shell script

sed:

sed '5!d' file

awk:

awk 'NR==5' file

Need to assign the contents of a text file to a variable in a bash script

In bash, $ (< answer.txt) is equivalent to $ (cat answer.txt), but built in and thus faster and safer. See the bash manual.

I suspect you're running this print:

NAME  
run-mailcap, see, edit, compose, print − execute programs via entries in the mailcap file

Convert .txt to .csv in shell

awk may be a bit of an overkill here. IMHO, using tr for straight-forward substitutions like this is much simpler:

$ cat ifile.txt | tr -s '[:blank:]' ',' > ofile.txt


Related Topics



Leave a reply



Submit