Here is a bash
script assuming your input file is named infile and the ranges are stored 1-per-line in a file named splits:
i=1
for range in $(< splits); do
sed -n "$(echo "$range" | cut -f1 -d, )p" infile > "file$i"
sed -n "$(echo "$range" | cut -f2 -d, )p" infile >> "file$i"
((i++))
done
This simply uses sed
to print the lines specified by the ranges, and saves each result as a new file (files created are named file1 file2 file3 etc). Two invocations of sed
are used to preserve the specified order of the rows.
Note that there is no format or error checking done by this simple script, and existing files named e.g. file1 will be overwritten.
A simplified alternative (courtesy of @muru) using while read
and letting bash split the ranges instead of cut:
i=1
while IFS=',' read n1 n2
do
sed -n "$n1 p; $n2 p" infile > "file$i"
((i++))
done < splits
If the order of the lines in the output files is important (e.g. rows 5,4 != 4,5), then the sed
bit will need to be broken up into two separate invocations similar to the first script.
If you want to use read
to pass the names, and you want to delete lines that contain the names:
read deletename; sed "/$deletename/d" test.txt
then press enter and read
waits for you to enter something, so type whatever you want deletename
to be, for example 0
, then press enter again and the sed
command is executed. The contents of test.txt
will appear in the terminal, but all the lines that contain 0
, or whatever you typed, will be deleted from the stream (NOT from the file)
If you only want to delete the names themselves it's like this:
read deletename; sed "s/$deletename//g" test.txt
If you then type 0
, then every instance of 0
will be deleted.
You can redirect (or tee
) the output to a new file, or if you want to modify the file in place, use the -i
flag (after testing)
read deletename; sed -i "/$deletename/d" test.txt
In this case you will see no output; the changes will be written to the file instead of displayed in the terminal (on STDOUT).
You need to use double quotes to allow parameter expansion, as single quotes will suppress it. but the most correct way, I think, although not necessary in this simple case, it to use single quotes around the other parts of the expression and quote the variable normally:
sed 's/'"$deletename"'//g' test.txt
Best Answer
Using
grep
: