Checking and replacing first line in text file, one-liner?

Hello,
I'm looking to check only the first line of a file to see if it is a format string, like

# -*- coding: utf-8; mode: tcl; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -\*- vim:fenc=utf-8:ft=tcl:et:sw=2:ts=2:sts=2

if the first line is anything else, insert the above string.

I'd appreciate a one liner as I'm putting this command inside of a

find . -depth -name "*.tcl" -type f -writeable ! -executable -exec awk INSERT_COOL_LINER

so far I'm hacking awk that looks like

awk 'NR==1 && /^#./ {print "format string exists";exit 1} {print "no format string";exit 1}' test.tcl

which correctly detects if the format string is there or not but can't seem to figure out how to get awk to redirect the pipe to insert the format string?

Thanks

gnu?

string='# -*- coding: utf-8; mode: tcl; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -\\*- vim:fenc=utf-8:ft=tcl:et:sw=2:ts=2:sts=2'

sed -i '1{/^#./! s/.*/'"$string"'/}' test.tcl
1 Like

Sweet! Thanks.

Did you want to replace the first line or insert before it? If the latter, try

sed  -i -e "1{/^#./! i$string" -e"}" file

or

sed  -i -e "1{/^#./! s/.*/$string\n&/" -e"}" file