Reputation: 7109
I have a number of text files (700+) and I need to get each file's name into the start of every line in the file.
Example, for filename myfile0072.txt
:
mike 160
jane 174
to
myfile0072.txt mike 160
myfile0072.txt jane 174
I don't have access to Bash or C or Perl or anything at work. Is there something I can do in Vim to get that results?
Upvotes: 2
Views: 3711
Reputation: 72726
There are two stages to this, firstly get all the files you want to edit into the argument list, then add the filename to the lines.
1) Add files to argument list.
Either start vim with "gvim *.txt" (if your shell can handle 700 files listed on the command line) or, load gvim with no files open (so the argument list is empty) and then:
cd /path/to/files
" Get the list of files
let filelist = glob('*.txt')
" Add files to the argument list
for file in split(filelist, '\n')
exe 'argadd ' . file
endfor
EDIT:
A cleaner way of doing this is:
:cd /path/to/files
:exe 'args' glob('*.txt')
END OF EDIT
2) Do the required filtering on all files:
:argdo %s/^/\=expand('%:t') . ' '/ | w
Explanation:
argdo
runs the command on every file in the argument list.
%s/FROM/TO/
replaces FROM with TO
^
is the start of the line (so the replacement adds TO to the start of the line)
\=
means that TO should be the result of an expression
expand('%:t')
gives the name of the current file (%), only including the tail (':t'), so no leading directory name.
. ' '
appends a space.
|
is the command joining character, so after the substitution, it runs:
w
, which writes the file to disk.
Upvotes: 7
Reputation: 7109
I went with as jleedev suggested since it was most familiar to me
:g/^/pu!%
:g/^/j
For some reason, with multi files open in vim, pu!% made the directory structure come into the file as well. No biggie.
I opened 200 files with the same instance of vim then did this...
qm
'q' to start recording a macro named 'm.
:g/^/pu!%
:g/^/j
:%s/blahhh/blahhhhhh
:w
:bn
the blahh stuff replaces the directory with blank, :w saves the files and :bn moves to the next file
q
q to end the macro
200@m
200@m means repeat macro m 200 times (because I had 200 files open)
I just did 4 times to get through all of my ~700 files.
Thanks for the help everyone!
Upvotes: 0
Reputation: 328840
The most simple option is
:%s:^:myfile0072.txt:
Explanation: :
: command, %
: for every line, s:^:xxx:
: Replace the "start of line" with "xxx". I'm not aware that you have some kind of variable substitution, though. But you can use <Ctrl-R>%
(which expands to the current filename).
But for 700 files, this seems to be very tedious. I'm wondering about your comment "I have no bash". You must have some kind of shell or you couldn't start vi.
Upvotes: 1
Reputation: 177885
How about
:g/^/pu!%
:g/^/j
to insert the filename at the beginning of each line in the current file.
To run this over many files, look into argdo
or bufdo
.
Upvotes: 3