我正在学习awk并且我很难尝试这样做:
我有一个文件,我们将其命名为pattern_file.txt
,其中包含多个模式,每行一个。例如,它看起来像这样:
pattern_file.txt
PATTERN1
PATTERN2
PATTERN3
PATTERN4
我有第二个文件,包含一些文字。我们将其命名为text_file.txt
。它看起来像这样:
text_file.txt
xxxxxxxxPATTERN1xxxxxxx
yyyyyPATTERN2yyyy
zzzzzzzzzPATTERN3zzzzzz
我要做的是:如果在pattern_file.txt
中读取的当前行中存在text_file.txt
中的某个模式,请打印该行。
我知道如何用awk打印一行,让我很难的是使用pattern_file.txt
中存储的模式并验证其中是否存在其中一种模式。
答案 0 :(得分:2)
使用index
awk 'NR==FNR{a[$1];next}{for(i in a)if(index($0,i)) print}' pattern text
xxxxxxxxPATTERN1xxxxxxx
yyyyyPATTERN2yyyy
zzzzzzzzzPATTERN3zzzzzz
将“模式”存储到散列中,并使用index
使用 <?php
if($_FILES["photo"]["error"] > 0){
echo "Error: " . $_FILES["photo"]["error"] . "<br>";
} else{
echo "File Name: " . $_FILES["photo"]["name"] . "<br>";
echo "File Type: " . $_FILES["photo"]["type"] . "<br>";
echo "File Size: " . ($_FILES["photo"]["size"] / 1024) . " KB<br>";
echo "Stored in: " . $_FILES["photo"]["tmp_name"];
}
?>
<?php
if(isset($_FILES["photo"]["error"])){
if($_FILES["photo"]["error"] > 0){
echo "Error: " . $_FILES["photo"]["error"] . "<br>";
} else{
$allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png");
$filename = $_FILES["photo"]["name"];
$filetype = $_FILES["photo"]["type"];
$filesize = $_FILES["photo"]["size"];
// Verify file extension
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!array_key_exists($ext, $allowed)) die("Error: Please select a valid file format.");
// Verify file size - 5MB maximum
$maxsize = 5 * 1024 * 1024;
if($filesize > $maxsize) die("Error: File size is larger than the allowed limit.");
// Verify MYME type of the file
if(in_array($filetype, $allowed)){
// Check whether file exists before uploading it
if(file_exists("upload/" . $_FILES["photo"]["name"])){
echo $_FILES["photo"]["name"] . " is already exists.";
} else{
move_uploaded_file($_FILES["photo"]["tmp_name"], "upload/" . $_FILES["photo"]["name"]);
echo "Your file was uploaded successfully.";
}
} else{
echo "Error: There was a problem uploading your file - please try again.";
}
}
} else{
echo "Error: Invalid parameters - please contact your server administrator.";
}
?>
尝试从记录中找到“模式”。
答案 1 :(得分:1)
此有用James Brown's answer的变体使用match()
regex 匹配(和)返回匹配字符串的起始索引,
awk 'FNR==NR{a[$0]; next}{for (i in a) if (match($0,i)) print}' pattern_file.txt text_file.txt
返回所需的行。
从match()
功能
awk 'FNR==NR{a[$0]; next}{for (i in a) if (match($0,i)) print RSTART}' pattern_file.txt text_file.txt
输出为
9 # Meaning 'PATTERN1' match started at index 9 in 'xxxxxxxxPATTERN1xxxxxxx'
6
10