-1

I have one file with following entries

vdomain
v2host
v3server
v1adapter
vhost
v2domain
v1application

I want to separate all these entries into 4 different files like

file1 : should contain names starting with "v"

vdomain
vhost

file2 : should contain names starting with "v1"

v1application
v1adapter

file3 : should contain names starting with "v2"

v2host
v2domain

file4 : should contain names starting with "V3"

v3server
3

Using awk:

awk '/^v[^123]/ { print >"file1" }
     /^v1/ { print >"file2" }
     /^v2/ { print >"file3" }
     /^v3/ { print >"file4" }' inputfile

This will create your four files.

The first regular expression matches only lines starting with a v not followed by the digits 1, 2 or 3 (since these are to go in the other files). Lines not matching any of the regular expressions are discarded.

The equivalent thing with sed:

sed -n \
    -e '/^v[^123]/w file1' \
    -e '/^v1/w file2' \
    -e '/^v2/w file3' \
    -e '/^v3/w file4' inputfile

The w command in sed writes the current line to the named file.

And with a shell loop (you don't really want to use this):

rm -f file[1234]
while read -r words; do
    case "$words" in
        v1*) printf '%s\n' "$words" >>file2 ;;
        v2*) printf '%s\n' "$words" >>file3 ;;
        v3*) printf '%s\n' "$words" >>file4 ;;
        v*)  printf '%s\n' "$words" >>file1 ;;
    esac
done <inputfile

This is almost the same except that whitespaces after each input line will be removed, also initial whitespaces are ignored and dropped. Here, the order of the tests is also important.

And finally, with ed, with a script that is, unsurprisingly, identical to the one used with sed:

cat <<ED_END | ed -s inputfile
/^v[^123]/w file1
/^v1/w file2
/^v2/w file3
/^v3/w file4
ED_END

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.