Store File name in same file

Hi All,

Needs to store file name in to the same file..
Ex: I have fixed width files under /usr/tmp/
A.txt
B.txt
C.txt
.......
N.txt

O/P
A.txt
1 KING A.txt
2 QUEEN B.txt

B.txt
1 Hello B.txt
2 COOL B.txt
3 KILL B.txt

....
....

Could you please help me out in this

My Try on this is

find . -name '*' -exec ls {} \;

Regards,
Sekhar

Where is the text supposed to be coming from? The output doesn't explain much when we don't know the input.

#!/bin/sh

# Usage: SCRIPT file1 file2 ...

TEMP=`tempfile`
for f; do
    awk 'NR==1{print FILENAME}1' "$f" >$TEMP
    mv $TEMP "$f"
done
rm $TEMP

If you don't have "tempfile" you can use
TEMP=/tmp/$$

1 Like

Thanks for your reply, Every record in the file has to store the fille name....

I/P
A.txt
1 KING
2 QUEEN

B.txt
1 Hello
2 COOL
3 KILL

O/P
A.txt
1 KING A.txt
2 QUEEN B.txt

B.txt
1 Hello B.txt
2 COOL B.txt
3 KILL B.txt

I'm guessing the first b.txt is a typo then, since the file is a.txt?

A slight change to that awk script might work, then:

#!/bin/sh

# Usage: SCRIPT file1 file2 ...

# If you don't have tempfile, try mktemp.
# if you don't have mktemp, try TEMP=/tmp/$$.
TEMP=`tempfile`
for f; do
    awk '{print $0, FILENAME}' "$f" >$TEMP
    # cat is better than mv because it won't alter the original's
    # ownership or access flags.
    cat $TEMP > "$f"
done

rm -f $TEMP

Neat use of 'for', yazu, didn't know it could take input from $1...$N like that.

2 Likes

Sorry, what needs to be replaced instead of tempfile... I tried to place input dir /temp/files/
TEMP=`tempfile`

Please help me in this...

What input dir? It doesn't have an input dir. The comments tell you how to use it:

# Usage: SCRIPT file1 file2 ...

so you could run my unmodified script as ./myscript /temp/files/*

Or you could modify the script as

# If you don't have tempfile, try mktemp.
# if you don't have mktemp, try TEMP=/tmp/$$.
TEMP=`tempfile`
for f in /path/to/input/* ; do
    awk '{print $0, FILENAME}' "$f" >$TEMP
    # cat is better than mv because it won't alter the original's
    # ownership or access flags.
    cat $TEMP > "$f"
done

rm -f $TEMP