Using Vim to get filename in files
I have multiple text files (700+) and I need to get each filename at the start of every line in the file.
Example, for a 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 these results?
source to share
There are two steps to this: first get all the files you want to edit into the argument list, then add the filename to the lines.
1) Add files to the argument list.
Start vim with "gvim * .txt" (if your shell can handle the 700 files listed on the command line) or load gvim without opening any files (so the argument list is empty), 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 to do it:
:cd /path/to/files
:exe 'args' glob('*.txt')
END EDIT
2) Do the necessary filtering for all files:
:argdo %s/^/\=expand('%:t') . ' '/ | w
Explanation:
argdo
runs the command for each file in the argument list.
%s/FROM/TO/
replaces FROM with TO
^
- this is the beginning of the line (so the replacement adds TO to the beginning of the line)
\=
means TO must be the result of the expression
expand('%:t')
gives the name of the current file (%) including only the tail (': t'), so there is no leading directory name.
. ' '
adds a space.
|
is a command concatenation character, so after substitution it runs:
w
which writes the file to disk.
source to share
The easiest option:
:%s:^:myfile0072.txt:
Explanation:: :
command %
,: for each line s:^:xxx:
,: Replace "start of line" with "xxx". I dont know you have some kind of variable replacement. But you can use <Ctrl-R>%
(which expands to the current filename).
But for 700 files, it seems very tedious. I'm interested in your comment "I don't have bash". You must have some kind of shell or cannot run vi.
source to share
I went with the suggested Jedi because he was the most familiar to me
:g/^/pu!%
:g/^/j
For some reason, when multiple files are opened in vim, pu!% Caused the directory structure to enter the file. No biggie.
I opened 200 files with the same vim instance, then did this ...
qm
'q' to start recording a macro named 'm.
:g/^/pu!%
:g/^/j
:%s/blahhh/blahhhhhh
:w
:bn
blahh stuff replaces directory with empty: w saves files and: bn moves to next file
q
q to terminate the macro
200@m
200 @m means repeating the macro m 200 times (because I had 200 files open)
I just did 4 times to go through all my ~ 700 files.
Thanks for helping everyone!
source to share