0

Given a file, /opt/file.dat, how do I insert the path to the file (/opt) as the first line of file.dat?

2
  • As the first line of what? Can you give examples?
    – gardenhead
    Jan 17, 2016 at 1:19
  • Hi, I have a text file called file.dat and located D\CC3\cc3_15_1. I would like to insert a line within file.dat which tells its path (D\CC3\cc3_15_1) as first line of the file. Jan 18, 2016 at 8:49

2 Answers 2

0

I think you can find some nifty one liners and make aliases out of them, but typically once you have a handful of commands a script is better because it is more flexible, hopefully more readable, and you can expand its functionality later a lot easier once you say "Oh! I should also make it do x...". So, here's one way to do it:

#!/bin/bash

# Add filepath to first line of file

myFile="file.dat"
filePath=`pwd`
tmpFile="tmpFile"

cp $myFile $tmpFile
echo $filePath | cat - $tmpFile > $myFile
rm $tmpFile

exit 0

Don't forget to make it executable: chmod u+x addPath.sh (assumes you saved the above script to a file addPath.sh).

3
  • For example, one useful way to expand this script is to add a bash for loop to get not only "file.dat" but all files in the working directory, or all files matching a pattern (say, *.c).
    – tniles
    Jan 16, 2016 at 18:54
  • Hi, Thank you it worked. As you suggested I try to make a loop to add as first line in each file contained in the working directory, the path of these files. I keep your script and add before the command: <For $$myFile IN (.) DO ( cp $myFile $tmpFile echo $filePath | cat - $tmpFile > $myFile rm $tmpFile exit 0) > But I get the error message "syntax error near unexpected token '(' " Any idea why ? Jan 18, 2016 at 13:46
  • You would need to do something like `ls` instead of the . you have. There are a lot of examples available online for bash for loops.
    – tniles
    Jan 19, 2016 at 22:43
0

Just display the path of the file then the whole file and redirect in into the file

PATH_TO_FILE=/path/to/file

TMP_FILE=`mktemp`

echo $PATH_TO_FILE | cat - $PATH_TO_FILE > $TMP_FILE & cp $TMP_FILE $PATH_TO_FILE

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .