0

I'm trying to add the filename of a text file into the first line of a the same text file. for example if the file name is called test1.txt, then the first line when you open the file should be test1.

below is what I've done so for, the only problem i have is that the word "$file" is being written to the file not the file name. any help is appreciated.

for file in *.txt; do
sed -i '1 i\$file' $file;
awk 'sub("$", "\r")' "$file" >  "$file"1;
mv "$file"1 "$file";
done
Cyrus
  • 84,225
  • 14
  • 89
  • 153
user2334436
  • 949
  • 5
  • 13
  • 34
  • 2
    See: [Difference between single and double quotes in bash](http://stackoverflow.com/q/6697753/3776858) – Cyrus Sep 29 '17 at 19:56
  • What are you hoping `sub("$", "\r")` will do? – Ed Morton Sep 29 '17 at 20:04
  • 1
    @user2334436 adding two small sample input files with expected output would help a lot.. it is not clear at all... you mention `test1` to be added if filename is `test1.txt`... but your code doesn't attempt to do that... if you have GNU sed, I think what you need is - `sed -i '1F' *.txt` if full filename is to be added – Sundeep Sep 30 '17 at 04:31

3 Answers3

2

Without concise, testable sample input and expected output it's an untested guess but it SOUNDS like all you need is:

awk -i inplace -v ORS='\r\n' 'FNR==1{print FILENAME}1' *

No shell loop or multiple commands required.

The above uses GNU awk for inplace editing and I'm assuming the sub() in your code was intended to add a \r at the end of every line.

Ed Morton
  • 188,023
  • 17
  • 78
  • 185
1

I've just started learning more about sed and awk and put this into a file called insert.sed and sourced it and passed it a file name:

sed -i '1s/^./'$1'\'$'\n/g' $1

In trying it, it seems to work okay:

rent$ cat x.txt 

<<< Who are you?

rent$ source insert.sed x.txt

rent$ cat x.txt 

x.txt

<< Who are you?

It is cutting off the first character of the first line so I'd have to fix that otherwise it does add the file name to first line.

I'm sure there's better ways of doing it.

Piyin
  • 1,823
  • 1
  • 16
  • 23
srsr98
  • 11
  • 2
  • It should be obvious, but the fix is to just match beginning of line: sed -i '1s/^./'$1'\'$'\n/g' $1 – srsr98 Oct 05 '17 at 14:14
0

If you want test1 on first line, with gnu sed

sed -i '1{x;s/.*/fich=$(ps -p $PPID -o args=);fich=${fich##*\\} };echo ${fich%%.*}/e;G}' test1.txt
ctac_
  • 2,413
  • 2
  • 7
  • 17