how to paste part of the file name to the content of file?
plain bash
for file in *.bam_dp; do
contents=$(< "$file")
echo "$contents ${file%%.*}" > "$file"
done
for multi-line files, still can be accomplished with plain bash
for file in *.bam_dp; do
mapfile -t contents < "$file"
printf "%s\n" "${contents[@]/%/ ${file%%.*}}" > "$file"
done
notes:
- the
mapfile
command reads the file into an array of lines. - the
${var/pattern/string}
parameter expansion does a search-and-replace on the variable value. (documented in the manual)- if pattern starts with
%
the pattern is anchored at the end of the string. Here, I'm matching the empty pattern at the end of the string. - the variable can be an array expansions, in which case the replacement occurs for each array element.
- if pattern starts with
Frankly, this approach is too clever, and I'd go for something more obvious.
Use a loop:
#!/bin/bash
shopt -s nullglob
for file in ???????.mapped.*bam_dp; do
[[ -f "$file" ]] || continue
id=${file%%.*} # grab the ID from file name
sed -i "s/$/ $id/" "$file" # modify the file in-place
done
Remove .* from $ARGV then append \t $ARGV to the file:
perl -i -pe '$ARGV=~s/\..*//; s/$/\t$ARGV/;' NA*
Glenn's solution is most likely faster to run:
perl -i -lpe '$_ .= " " . substr($ARGV,0,index($ARGV,"."))' NA*
though if each file is only a single line, most of the time will be seeking on the drive.