Feed on

Archive for the 'Shell Scripting' Category

to remove lines 2 through 18 of file foo.bar, call: sed -e ’2,18d’ foo.bar

insert a tab using sed

if you find that sed isn’t matching \t, the easiest workaround is to not use sed at all. instead, install ‘gsed’, which can handle tabs.

i’ve got a bunch of files with one line — a number — and i’d like to sort those filenames on the command line based on that number. to that in one line of shell code: for i in `ls *.*`; do echo “`head -n1 $i` $i” ; done | sort -n

to  send the standard output and standard error streams from your shell script somewhere, place the following at the top of your script: #!/bin/bash exec &>  output.file; [the rest of your code]

to measure how much time a program takes to execute from the command-line, use the ‘time’ function. for instance, to time the ‘date’ command: >> time date Wed Oct 31 14:12:41 EDT 2007 real    0m0.003s user    0m0.000s sys     0m0.002s

to count the number of times you match a substring in a larger text file, you can use the following shell one-liner: >> sed “s/[sub_str]/[sub_str]\n/g” [text_file] | wc -l

to spread a one-line command over multiple lines in a shell script, end each line with a slash and indent the next line.  for instance: cat $1 | sed ‘s/>FALF/F_FAL/g’  \ | sed ‘s/>FAL1/1_FAL/g’  \ | sed ‘s/>FAL5/5_FAL/g’  \ | sed ‘s/>FALZ/Z_FAL/g’  \ | sed ‘s/>OUTGROUP/5_OUTGROUP/’ > $2

turns out floating point division (or any other type of floating point math) isn’t built-into the bash shell.  instead, you’ll have to use the bc utility: echo “6.0/10″ | bc -l

test file existence in bash

file existence can be tested for in a conditional using the -a operator: if [ -a filename.txt ] then echo “file here!” fi

let’s say you’ve got: $j=”foo” and you’d like to tack on its good partner ‘bar’. then, use the dollar sign and curly braces to delineate variable from string: $k=”${j}bar”

Next »