I need to extract a certain line number from a file and then append it another file. New with bash,Please help!
Asked
Active
Viewed 935 times
2 Answers
2
head -n<SkipLines> <filename> | tail -n<TakeLines>
so if you want to take 2 lines from the 10th of a file pippo.txt:
head -n10 pippo.txt | tail -n2
EDIT:
To append it to another file just do:
head -n<SkipLines> <filename> | tail -n<TakeLines> >> <OtherFile>
head -n10 pippo.txt | tail -n2 >> pippo2.txt

Stefano d'Antonio
- 5,874
- 3
- 32
- 45
1
Assuming Bash≥4.
To extract line 42 from file inputfile
and append it to file outputfile
is as simple as:
# data
input=inputfile
output=outputfile
linenb=42
# get line number
mapfile -t -s $((linenb-1)) -n 1 line < "$input" || exit 1
# check that we got a line
if ((${#line[@]}==0)); then
printf >&2 'Line %d not found in file %s\n' "$linenb" "$input"
exit 1
fi
# append it to output file
printf '%s\n' "$line" >> "$output"
Pure Bash!

gniourf_gniourf
- 44,650
- 9
- 93
- 104
-
Sounds like a little bit of an overhead loading the whole file into an array in memory just to use N lines from that file. – Andreas Louv Jun 13 '16 at 17:27
-
@andlrc: it doesn't load the whole file at all: it _skips_ the first lines (that's what the `-s` option does) and _stops after reading one line_ (that's what the `-n 1` option does). It's very efficient! – gniourf_gniourf Jun 13 '16 at 17:28
-
I see, thanks for clarifying :-) I'm gonna read up on `mapfile` – Andreas Louv Jun 13 '16 at 17:31