我有一個頂級目錄路徑,我想將所有相對路徑轉換爲該目錄內所有文件中存在的絕對路徑。 例如我有這樣的目錄結構:將相對路徑轉換爲絕對路徑的Bash&Perl腳本
內容top_level.ext1
$ tree
.
|-- DIR
| |-- inner_level.ext1
| `-- inner_level.ext2
|-- top_level.ext1
`-- top_level.ext2
:
../../a/b/c/filename_1.txt
../../a/d/e/filename_2.txt
假設頂級目錄路徑是/this/is/the/abs/dir/path/
想要的top_level.ext1
內容轉換爲:
/this/is/the/abs/a/b/c/filename_1.txt
/this/is/the/abs/a/d/e/filename_2.txt
內容top_level.ext2
:
cc_include+=-I../../util1/src/module1/moduleController -I../../util/src/module1/module2Controller;
cc_include+=-I../../util2/src/module2/moduleUtility;
想要的top_level.ext2
到的內容轉換:
cc_include+=-I/this/is/the/abs/util1/src/module1/moduleController -I/this/is/the/abs/util/src/module1/module2Controller;
cc_include+=-I/this/is/the/abs/util2/src/module2/moduleUtility;
另外,想通過內部DIR文件應用此相同的轉換。
例如 內容DIR/inner_level.ext1
:
../../../a/b/c/filename_1.txt
../../../a/d/e/filename_2.txt
希望將內容轉換的DIR/inner_level.ext1
到:
/this/is/the/abs/a/b/c/filename_1.txt
/this/is/the/abs/a/d/e/filename_2.txt
同爲DIR/inner_level.ext2
也。
已經寫了這兩個腳本。
top_level.ext1
的轉換成功。
file_manager.sh
:
#!/usr/bin/bash
file='resolve_path.pl'
basedir='/this/is/the/abs/dir/path'
run_perl(){
echo -e "\n File getting modified: $1"
cp $1 tmp.in
perl $file
mv tmp.out $1
rm tmp.in
}
find $basedir -type f |while read inputfile
do
run_perl $inputfile
done
resolve_path.pl
:
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
use 5.010;
use Switch;
#******************************************************
# Set-up Directory And Input/Output File Names
#******************************************************
our $in_file = glob('tmp.in');
my $out_file1 = 'tmp.out';
print "Input file: $in_file\n";
#************************************
# Local and Global Variables
#*************************************
my $current_path = "/this/is/the/abs/dir/path";
my $temp_path = $current_path;
#************************************
# Open Read and Write File
#************************************
open(READ, $in_file) || die "cannot open $in_file";
open(WRITE, ">$out_file1") || die "cannot open $out_file1";
#******************************************************
# Read The Input [*.out] File Line By Line
#******************************************************
while (<READ>) {
if(/^(\.\.\/){1,}(\w+\/)*(\w+).(\w+)/){
my $file_name = $3;
my $file_ext = $4;
my @count = ($_ =~ /\.\.\//g);
my $cnt = @count;
my @prev_dir = ($_ =~ /\w+\//g);
my $prev_dir_cnt = @prev_dir;
my $file_prev_dir = join('', @prev_dir);
$temp_path = $current_path;
for(my $i=0; $i<$cnt; $i++){
if($temp_path =~m/(\/.*)\/\w+/){
$temp_path = $1;
}
}
print WRITE "$temp_path"."\/"."$file_prev_dir"."$file_name"."\."."$file_ext"."\n";
} else {
print WRITE "$_";
}
}
我面臨的問題:
沒有轉換被應用在
top_level.ext2
&DIR/inner_level.ext2
因爲我的Perl腳本不能正確解析爲../
(即cc_include+=-I
即將開始)。從絕對路徑相對路徑轉換工作不正常 爲
DIR/inner_level.ext1
和錯誤的路徑越來越 追加。
如果有人可以在我的腳本中提出預期的更改以解決上述兩個問題,那將會很有幫助。